import pymysql.cursors
from config.config import settings


class Database:
    def __init__(self):
        self.connection = pymysql.connect(host=settings.database_url,
                                          port=settings.database_port,
                                          user=settings.database_user,
                                          password=settings.database_password,
                                          database=settings.database_db,
                                          cursorclass=pymysql.cursors.DictCursor)

    def open_connection(self):
        if not self.connection:
            self.connection = pymysql.connect()
        return self.connection

    def close_connection(self):
        if self.connection:
            self.connection.close()
            self.connection = None

    def get_data_from_mysql(self):
        result = []
        try:
            connection = self.open_connection()
            sql = "SELECT product_name, description, discount_info FROM douyin_live_yellow_car_products;"
            with connection.cursor() as cursor:
                cursor.execute(sql)
                result = cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            self.close_connection()
        return result
